package com.lizhi.menu.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lizhi.menu.Dto.AddressDto;
import com.lizhi.menu.common.entity.ApplicationException;
import com.lizhi.menu.common.enums.ResultCode;
import com.lizhi.menu.domain.Address;
import com.lizhi.menu.mapper.AddressMapper;
import com.lizhi.menu.service.IAddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


/**
 * 地址Service业务层处理
 *
 * @author lizhi
 * @date 2023-05-18
 */
@Service
@RequiredArgsConstructor
public class AddressServiceImpl implements IAddressService {
    private final AddressMapper addressMapper;

    /**
     * 查询地址
     *
     * @param id 地址主键
     * @return 地址
     */
    @Override
    public Address getInfo(String id) {
        return new Address().selectById(id);
    }

    /**
     * 查询地址列表
     *
     * @param dto 地址
     * @return 地址
     */
    @Override
    public Page<Address> list(AddressDto dto) {
        return addressMapper.selectAddressList(dto.createPage(),dto);
    }

    /**
     * 新增地址
     *
     * @param address 地址
     * @return 结果
     */
    @Override
    public void add(Address address) {
        Address address1 = addressMapper.selectOne(Wrappers.<Address>lambdaQuery()
                .and(add -> add.eq(Address::getUsername, address.getUsername())
                        .eq(Address::getUsertel, address.getUsertel()))
                .last("limit 1"));
        if (!ObjectUtils.isEmpty(address1)){
            throw new ApplicationException(ResultCode.FAILURE,"用户姓名或者用户手机号重复");
        }
        addressMapper.insert(address);
    }

    /**
     * 修改地址
     *
     * @param address 地址
     * @return 结果
     */
    @Override
    public void edit(Address address) {
        Address address1 = addressMapper.selectOne(Wrappers.<Address>lambdaQuery()
                .and(add -> add.eq(Address::getUsername, address.getUsername())
                        .eq(Address::getUsertel, address.getUsertel()))
                .ne(!ObjectUtils.isEmpty(address.getId()),Address::getId,address.getId())
                .last("limit 1"));
        if (!ObjectUtils.isEmpty(address1)){
            throw new ApplicationException(ResultCode.FAILURE,"用户姓名或者用户手机号重复");
        }
        addressMapper.updateById(address);
    }

    /**
     * 删除地址信息
     *
     * @param id 地址主键
     * @return 结果
     */
    @Override
    public void remove(String id) {
        addressMapper.deleteById(id);
    }
}
